package com.shapawan.tourism.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shapawan.tourism.common.Result;
import com.shapawan.tourism.entity.AdminUser;
import com.shapawan.tourism.service.AdminUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.util.Date;

/**
 * 管理员控制器
 */
@Api(tags = "管理员管理")
@RestController
@RequestMapping("/admin")
@CrossOrigin // 添加跨域支持
@Slf4j
public class AdminController {

    @Autowired
    private AdminUserService adminUserService;
    
    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @ApiOperation("获取管理员列表")
    @GetMapping("/list")
    public Result<Page<AdminUser>> list(
            @RequestParam(value = "page", defaultValue = "1") Integer page,
            @RequestParam(value = "size", defaultValue = "10") Integer size,
            @RequestParam(value = "keyword", required = false) String keyword,
            @RequestParam(value = "role", required = false) String role) {
        
        log.info("获取管理员列表: page={}, size={}, keyword={}, role={}", page, size, keyword, role);
        
        // 移除权限检查，允许所有访问
        Page<AdminUser> pageParam = new Page<>(page, size);
        LambdaQueryWrapper<AdminUser> queryWrapper = new LambdaQueryWrapper<>();
        
        // 构建查询条件
        boolean hasCondition = false;
        
        // 如果有关键字，添加查询条件
        if (keyword != null && !keyword.trim().isEmpty()) {
            queryWrapper.and(wrapper -> wrapper
                .like(AdminUser::getUsername, keyword)
                .or()
                .like(AdminUser::getName, keyword)
            );
            hasCondition = true;
        }
        
        // 如果有角色筛选
        if (role != null && !role.trim().isEmpty()) {
            queryWrapper.eq(AdminUser::getRole, role);
            hasCondition = true;
        }
        
        // 添加排序条件 - admin用户置顶，然后按创建时间倒序
        queryWrapper.last("ORDER BY username = 'admin' DESC, create_time DESC");
        
        log.info("查询条件: {}", queryWrapper.getCustomSqlSegment());
        
        Page<AdminUser> adminPage = adminUserService.page(pageParam, queryWrapper);
        
        // 不返回密码字段
        adminPage.getRecords().forEach(admin -> admin.setPassword(null));
        
        return Result.success(adminPage);
    }

    @ApiOperation("获取管理员详情")
    @GetMapping("/{id}")
    public Result<AdminUser> getDetail(@PathVariable Integer id) {
        AdminUser adminUser = adminUserService.getById(id);
        if (adminUser == null) {
            return Result.failed("管理员不存在");
        }
        
        // 不返回密码
        adminUser.setPassword(null);
        return Result.success(adminUser);
    }

    @ApiOperation("添加管理员")
    @PostMapping("/add")
    public Result<String> add(@RequestBody AdminCreateRequest request) {
        log.info("添加管理员: {}", request.getUsername());
        
        // 检查用户名是否存在
        AdminUser existAdmin = adminUserService.getByUsername(request.getUsername());
        if (existAdmin != null) {
            return Result.failed("用户名已存在");
        }
        
        AdminUser adminUser = new AdminUser();
        adminUser.setUsername(request.getUsername());
        adminUser.setName(request.getName());
        // 密码加密存储
        adminUser.setPassword(passwordEncoder.encode(request.getPassword()));
        adminUser.setRole(request.getRole());
        adminUser.setPhone(request.getPhone()); // 设置手机号
        adminUser.setStatus("正常".equals(request.getStatus()) ? 1 : 0);
        
        // 创建时间和更新时间由MyBatis Plus自动填充
        
        boolean success = adminUserService.save(adminUser);
        if (success) {
            return Result.success("添加成功");
        } else {
            return Result.failed("添加失败");
        }
    }

    @ApiOperation("更新管理员")
    @PutMapping("/update")
    public Result<String> update(@RequestBody AdminUpdateRequest request) {
        log.info("更新管理员请求: {}", request);
        
        // 禁止修改admin用户
        if ("admin".equals(request.getUsername())) {
            return Result.failed("无法修改系统管理员");
        }
        
        AdminUser adminUser = adminUserService.getById(request.getId());
        if (adminUser == null) {
            return Result.failed("管理员不存在");
        }
        
        log.info("更新前的管理员信息: id={}, updateTime={}", adminUser.getId(), adminUser.getUpdateTime());
        
        // 更新信息
        adminUser.setUsername(request.getUsername()); // 确保更新用户名
        adminUser.setName(request.getName());
        adminUser.setRole(request.getRole());
        adminUser.setPhone(request.getPhone()); // 设置手机号
        
        // 处理状态，确保正确转换
        if (request.getStatus() != null) {
            adminUser.setStatus("正常".equals(request.getStatus()) ? 1 : 0);
        } else {
            // 如果状态为空，默认为正常
            adminUser.setStatus(1);
        }
        
        // 如果提供了新密码，则更新密码
        if (request.getPassword() != null && !request.getPassword().isEmpty()) {
            adminUser.setPassword(passwordEncoder.encode(request.getPassword()));
        }
        
        log.info("更新管理员信息: {}", adminUser);
        
        // 更新时间由MyBatis Plus自动填充
        boolean success = adminUserService.updateById(adminUser);
        
        // 再次查询显示更新后的时间
        if (success) {
            AdminUser updatedUser = adminUserService.getById(request.getId());
            log.info("更新后的管理员信息: id={}, updateTime={}", updatedUser.getId(), updatedUser.getUpdateTime());
            return Result.success("更新成功");
        } else {
            return Result.failed("更新失败");
        }
    }

    @ApiOperation("删除管理员")
    @DeleteMapping("/{id}")
    public Result<String> delete(@PathVariable Integer id) {
        log.info("删除管理员: id={}", id);
        
        AdminUser adminUser = adminUserService.getById(id);
        if (adminUser == null) {
            return Result.failed("管理员不存在");
        }
        
        // 禁止删除admin用户
        if ("admin".equals(adminUser.getUsername())) {
            return Result.failed("无法删除系统管理员");
        }
        
        boolean success = adminUserService.removeById(id);
        if (success) {
            return Result.success("删除成功");
        } else {
            return Result.failed("删除失败");
        }
    }
    
    /**
     * 创建管理员请求
     */
    @Data
    public static class AdminCreateRequest {
        @NotBlank(message = "用户名不能为空")
        private String username;
        
        @NotBlank(message = "密码不能为空")
        private String password;
        
        @NotBlank(message = "姓名不能为空")
        private String name;
        
        @NotBlank(message = "角色不能为空")
        private String role;
        
        private String phone; // 添加手机号字段
        
        @NotBlank(message = "状态不能为空")
        private String status;
    }
    
    /**
     * 更新管理员请求
     */
    @Data
    public static class AdminUpdateRequest {
        @NotNull(message = "ID不能为空")
        private Integer id;
        
        @NotBlank(message = "用户名不能为空")
        private String username;
        
        @NotBlank(message = "姓名不能为空")
        private String name;
        
        @NotBlank(message = "角色不能为空")
        private String role;
        
        private String phone; // 添加手机号字段
        
        private String password; // 添加密码字段，编辑时可选
        
        private String status; // 移除NotBlank约束，允许为空
    }
} 